var $ = require("../../utils/Ajax.js");
let { ZegoClient } = require("../../utils/jZego-wx-1.1.1.js");
// let { format, sharePage } = require("../../utils/util.js");
let { getLoginToken } = require("../../utils/server.js");
let zg;
//获取应用实例
const app = getApp();
let { liveAppID: appID, wsServerURL, logServerURL, tokenURL } = app.globalData;

// pages/Live/Live.js
Page({
  data: {
    gaoduS: 1,
    // gaodu: "calc(100% - 233rpx)",
    gaodu: "375rpx",

    PictureUrl: getApp().PictureUrl,

    // 直播ID
    VideoId: null,

    Ticket: null,
    UserInfor: null,
    
    VideoInfor: null,
    VideoIsFriend: null,
    VideoGife: null,
    UserListCont: [],
    LiveVideo: null,

    // 公告内容
    RoomText: null,
    RoomCont: null,
    Comment:[1,2,3,4,5,6,7,8,9,10],

    // 中奖奖品
    TurntableLuckDraw: null,

    // 底部所有目录控制
    showShopPopup: false,
    animationData: {},

    // 大转盘控制
    showShopPopup1: false, 
    animationData1: {},
    ZhuanPanAnimation: '',
    // 大转盘ID
    TurntableId: null,

    // 拼团商品
    Assemble: null,

    // 秒杀商品
    Spike: null,

    // 本页记录控制
    showShopPopup2: false,
    animationData2: {},
    // 本场中奖记录
    LuckDraw: null,

    // 背包控制
    showShopPopup3: false,
    animationData3: {},
    Knapsack: [],

    // 排行榜控制
    showShopPopup4: false,
    animationData4: {},
    // 排行榜记录
    UserGifts: null,

    // 观众控制
    showShopPopup5: false,
    animationData5: {},

    // 充值控制
    showShopPopup6: false,
    animationData6: {},
    // 充值财富豆
    TopUpS: [
      { id: 1, number: 42, money: 6 },
      { id: 2, number: 84, money: 12 },
      { id: 3, number: 210, money: 30 },
      { id: 4, number: 420, money: 60 },
      { id: 5, number: 756, money: 108 },
      { id: 6, number: 3626, money: 518 },
    ],
    TopUpSIndex: 0,
    TopUpSMoney: null,
    TopUpSNumber: null,

    // 玩法介绍控制
    animationData7: {},
    // 玩法介绍模态框
    BgModule: false,
    // 玩法介绍模态框动画速度控制
    BgModuleSpeed: 300,

    // 充值控制
    showShopPopup8: false,
    animationData8: {},


    // 发起抽奖控制
    showShopPopup9: false,
    animationData9: {},

    // 购买门票控制
    showShopPopup10: false,
    animationData10: {},

    chouSelect: [
      { id: '1', name: '分享抽奖', name_: '分享直播间可抽' },
      { id: '2', name: '送礼物抽奖', name_: '送主播礼物可抽' }
    ],
    chouSelectIndex: 0,
    Gift: [],
    SelectGiftS: null,
    SelectGiftId: null,
    SelectGiftNum: 0,
    SelectGiftS1: null,
    SelectGiftId1: null,
    SelectGiftDan: 0,
    SelectGiftJia: 0,

    DongHuaBol: false,
    DongHuaSrc: null,

    // 更多状态
    MoreStatus: true,

    // 礼包
    libaoNav: ['全部','大转盘','抽奖'],
    libaoIndex: 0,

    loginType: 'audience',          // 登录类型。anchor：主播；audience：观众
    roomID: 812100002,             // 房间 ID
    roomName: 1,            // 房间名
    userID: 2,             // 当前初始化的用户 ID
    userName: 2,           // 当前初始化的用户名
    appID: "",              // appID，用于初始化 sdk
    anchorID: "",           // 主播 ID
    anchorName: "",         // 主播名
    anchorStreamID: "",     // 主播推流的流 ID
    publishStreamID: "",    // 推流 ID
    pusherVideoContext: {}, // live-pusher Context，内部只有一个对象
    playStreamList: [],     // 拉流流信息列表，列表中每个对象结构为 {anchorID:'xxx', streamID:'xxx', playContext:{}, playUrl:'xxx', playingState:'xxx'}
    beginToPublish: false,  // 准备连麦标志位
    reachStreamLimit: false,// 房间内达到流上限标志位
    isPublishing: false,    // 是否正在推流
    pushConfig: {           // 推流配置项
      mode: 'RTC',
      aspect: '3:4',        // 画面比例，取值为 3:4, 或者 9:16
      isBeauty: 6,          // 美颜程度，取值范围 [0,9]
      isMute: false,        // 推流是否静音
      showLog: false,       // 是否显示 log
      frontCamera: true,    // 前后置摄像头，false 表示后置
      minBitrate: 200,      // 最小视频编码码率
      maxBitrate: 500,      // 最大视频编码码率
    },
    playConfig: {
      mode: 'RTC',
    },
    preferPublishSourceType: 1, // 0：推流到 cdn；1：推流到 bgp
    preferPlaySourceType: 1,    // 0：auto；1：从 bgp 拉流
    upperStreamLimit: 4,        // 房间内限制为最多 4 条流，当流数大于 4 条时，禁止新进入的用户连麦
    tapTime: "",
    pushUrl: "",
    containerAdapt: "",
    containerBaseAdapt: "containerBase-big-calc-by-height",
    messageAdapt: "message-hide",
    requestJoinLiveList: [],    // 请求连麦的成员列表
    messageList: [],     // 消息列表，列表中每个对象结构为 {name:'xxx', time:xxx, content:'xxx'}
    isCommentShow: false,
    inputMessage: "",
    isMessageHide: true,
    scrollToView: "",
  },

  clickMe: function() {
    this.showModal();
  },

  xuanzhuan: function(){
    var gaodu = this.data.gaodu;
    if (gaodu == '375rpx'){
      this.setData({
        gaoduS: 1,
        gaodu: "calc(100% - 233rpx)",
      })
    }else{
      this.setData({
        gaoduS: null,
        gaodu: "375rpx",
      })
    }
  },

  onLoad: function (options) {
    var that = this;
    wx.setNavigationBarTitle({
      title: "直播"
    }) 

    // { roomID, roomName, loginType }
    let roomID = '812100002';
    let roomName = '张鹏';
    let loginType = 'audience';
    console.log('>>>[liveroom-room] onLoad, options are: ', roomID);
    roomName = roomName ? roomName : '';
    this.setData({
      roomID,
      roomName,
      loginType,
      preferPlaySourceType: 0,
      VideoId: options.VideoId,
      LiveVideoNextId: options.LiveVideoNextId,
      TopUpSMoney: that.data.TopUpS[that.data.TopUpSIndex].money
    });

    // 保持屏幕常亮
    wx.setKeepScreenOn({
      keepScreenOn: true,
    });

    $.Ajax("api/liveVideo","POST",{
      id: options.VideoId
    },function(res){
      if(res.s){
        that.setData({
          LiveVideo: res.d.LiveVideo,
          Ticket: res.d.LiveVideo.ticket,
          VideoInfor: res.d.user,
          VideoGife: res.d.userGift,
          VideoIsFriend: res.d.isFriend,
          LuckDraw: res.d.userLuckDraw,
          UserGifts: res.d.userGifts,
          Assemble: res.d.assemble,
          Spike: res.d.spike,
          Gift: res.d.gift,
          SelectGiftS: res.d.gift[0].title,
          SelectGiftId: res.d.gift[0].id,
          SelectGiftDan: Number(res.d.gift[0].price),
          SelectGiftS1: res.d.gift[0].title,
          SelectGiftId1: res.d.gift[0].id
        })
        if (res.d.hasTicket == 0){
          wx.showModal({
            title: '购买提示',
            content: '暂无观看权限,请先购买!',
            success: function (res) {
              if (res.confirm) {
                var animation = wx.createAnimation({
                  duration: 400,
                  timingFunction: "linear",
                  delay: 0
                })
                that.animation = animation;
                animation.translateY(520).step()
                that.setData({
                  animationData10: animation.export(),
                  showShopPopup10: true
                })
                setTimeout(() => {
                  animation.translateY(0).step()
                  that.setData({
                    animationData10: animation.export()
                  })
                }, 200)
              } else if (res.cancel) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
          setTimeout(function(){
            wx.navigateBack({
              delta: 1
            })
          },10000)
        }
      }
    })
    $.Ajax("api/turntable","GET",{},function(res){
      if(res.s){
        if (res.d.turntable != null){
          that.setData({
            TurntableId: res.d.turntable.id
          })
        }
      }else{
        wx.showToast({
          title: res.m,
          icon: 'success',
          duration: 2000
        })
      }
    })
  },

  MenPiaoSubmit: function(){
    var that = this;
    var Ticket = that.data.Ticket;
    var balance = that.data.UserInfor.balance;
    if (Ticket > balance){
      wx.showToast({
        title: '财富豆不足,请先充值',
        icon: 'none',
        duration: 2000
      })
      setTimeout(function () {
        wx.navigateTo({
          url: '../TopUpBeans/TopUpBeans',
        })
      }, 1000)
    }else{
      $.Ajax("api/ticket", "POST", {
        id: Number(that.data.LiveVideoNextId),
        t: 1
      }, function (res) {
        // that.MenPiaoBgClose();
        wx.showToast({
          title: res.m,
          icon: 'none',
          duration: 1500,
          mask: true
        })
      })
    }
  },

  // 点击查看用户资料
  Data: function(){
    wx.navigateTo({
      url: '../Data/Data',
    })
  },

  // 点击底部送礼
  SongGiftId: function(e){
    var SongGiftId = e.currentTarget.dataset.id;
    $.Ajax("api/gift","POST",{
      liveVideId: this.data.VideoId,
      giftId: SongGiftId
    },function(res){
      if(res.s){
        var SongLiDongHua = "ZhangPengQQ812100002_" + SongGiftId
        zg.sendRoomMsg(1, 1, SongLiDongHua,
          function (seq, msgId, msg_category, msg_type, msg_content) {
            console.log('>>>[liveroom-room] onComment success');
          }, function (err, seq, msg_category, msg_type, msg_content) {
            console.log('>>>[liveroom-room] onComment, error: ');
            console.log(err);
          });
      }else{
        wx.showToast({
          title: res.m,
          icon: 'success',
          duration: 2000
        })
        if (res.m == "余额不足") {
          setTimeout(function () {
            wx.navigateTo({
              url: '../TopUpBeans/TopUpBeans',
            })
          }, 2000)
        }
      }
    })
  },

  // 点击输入框,调整输入框位置
  Focus: function (e) {
    this.setData({
      focus: true,
      input_bottom: e.detail.height
    })
  },

  // 取消输入,恢复位置
  Blur: function(){
    this.setData({
      focus: false,
      input_bottom: 0
    })
  },

  // 显示遮罩层
  Catalog: function() {
    var gaoduS = this.data.gaoduS;
    if(gaoduS == 1){
      this.setData({
        gaodu: "calc(100% - 576rpx)"
      })
    }
    var animation = wx.createAnimation({
      duration: 400,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(452).step()
    this.setData({
      animationData: animation.export(), 
      showShopPopup: true
    })
    setTimeout(() => {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export() 
      })
    }, 200)
  },

  // 隐藏遮罩层
  CatalogClose: function() {
    var gaodu = this.data.gaodu;
    if (gaodu == '375rpx'){

    }else{

    }
    // this.setData({
    //   gaodu: "calc(100% - 233rpx)"
    // })
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(452).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showShopPopup: false
      })
    }.bind(this), 200)
  },

  // 分享
  onShareAppMessage: function () {
    var that = this;
    $.Ajax("api/userShare", "POST", {
      type: 2,
      objId: that.data.LiveVideo.id,
      objName: that.data.LiveVideo.title,
    }, function (res) {
      wx.showToast({
        title: res.m,
        icon: 'none',
        duration: 1500
      })
    })
    var shareObj = {
      title: that.data.LiveVideo.title,
      path: '/pages/Live/Live',
      imageUrl: 'http://pics.sc.chinaz.com/files/pic/pic9/201902/bpic10547.jpg',
      success: function (res) {}
    }
    return shareObj;
  },

  // 大转盘
  zhuan: function(){
    this.CatalogClose();
    this.setData({
      MoreStatus: true
    })
    var animation = wx.createAnimation({
      duration: 400,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(910).step()
    this.setData({
      animationData1: animation.export(),
      showShopPopup1: true
    })
    setTimeout(() => {
      animation.translateY(0).step()
      this.setData({
        animationData1: animation.export()
      })
    }, 200)
  },

  // 点击开始抽奖
  GoChouJiang: function (e) {
    var animation = wx.createAnimation({
      transformOrigin:"50% 50%",
      duration: 100,
      timingFunction: 'ease-out'
    })
    this.animation.rotate(180 * (100)).step();
    this.setData({
      ZhuanPanAnimation: this.animation.export()
    })
    var that = this;
    var Num = e.currentTarget.dataset.number;
    $.Ajax("api/turntableLuckDraw","GET",{
      id: that.data.TurntableId,
      liveVideId: that.data.VideoId,
      n: Number(Num)
    },function(res){
      if(res.s){
        that.Winning();
        that.setData({
          TurntableLuckDraw: res.d.turntablSetes
        })
      }else{
        wx.showToast({
          title: res.m,
          icon: 'success',
          duration: 2000
        })
      }
    })
  },

  // 展开中奖了
  Winning: function(){
    var animation = wx.createAnimation({
      duration: 300,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(620).step()
    this.setData({
      animationData8: animation.export(),
      showShopPopup8: true
    })
    setTimeout(() => {
      animation.translateY(0).step()
      this.setData({
        animationData8: animation.export()
      })
    }, 200)
  },

  // 关闭中奖了
  WinningClose: function(){
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(620).step()
    this.setData({
      animationData8: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData8: animation.export(),
        showShopPopup8: false
      })
    }.bind(this), 200)
  },

  // 关闭大转盘
  zhuanClose: function(){
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(910).step()
    this.setData({
      animationData1: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData1: animation.export(),
        showShopPopup1: false
      })
    }.bind(this), 200)
  },

  // 点击发起抽奖
  chou: function () {
    this.CatalogClose();
    var animation = wx.createAnimation({
      duration: 400,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(620).step()
    this.setData({
      animationData9: animation.export(),
      showShopPopup9: true
    })
    setTimeout(() => {
      animation.translateY(0).step()
      this.setData({
        animationData9: animation.export()
      })
    }, 200)
  },

  // 点击选择抽奖类型
  ClickchouSelect: function (e) {
    var Index = e.currentTarget.dataset.index_;
    this.setData({
      chouSelectIndex: Index
    })
  },

  // 选择礼物名称
  Gift:function(e){
    var Gift = this.data.Gift;
    this.setData({
      SelectGiftS: Gift[e.detail.value].title,
      SelectGiftId: Gift[e.detail.value].id,
      SelectGiftDan: Number(Gift[e.detail.value].price),
      SelectGiftJia: Number(Gift[e.detail.value].price) * this.data.SelectGiftNum
    })
  },

  // 选择礼物名称
  Gift1: function (e) {
    var Gift = this.data.Gift;
    this.setData({
      SelectGiftS1: Gift[e.detail.value].title,
      SelectGiftId1: Gift[e.detail.value].appID
    })
  },

  // 抽奖个数
  SelectGiftNum: function (e){
    var SelectGiftDan = this.data.SelectGiftDan;
    this.setData({
      SelectGiftNum: e.detail.value,
      SelectGiftJia: SelectGiftDan * e.detail.value
    })
  },

  // 点击关闭抽奖
  chouClose: function (e) {
    var that = this;
    var Status = e.currentTarget.dataset.status;
    var animation = wx.createAnimation({
      duration: 400,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(452).step()
    this.setData({
      animationData9: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData9: animation.export(),
        showShopPopup9: false
      })
    }.bind(this), 200)
    if (Status == 1){
      $.Ajax("api/addLuckDraw","POST",{
        type: that.data.chouSelectIndex,
        giftId: that.data.SelectGiftId,
        num: that.data.SelectGiftNum,
        givingGiftId: that.data.SelectGiftId1,
        amount: that.data.SelectGiftJia
      },function(res){
        if(res.s){
          wx.showToast({
            title: res.m,
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  },

  pin: function(e){
    var Id = e.currentTarget.dataset.id;
    var Type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: '../ShopDetails/ShopDetails?Id=' + Id + '&Type=' + Type,
    })
  },

  miao: function(e){
    var Id = e.currentTarget.dataset.id;
    var Type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: '../ShopDetails/ShopDetails?Id=' + Id + '&Type=' + Type,
    })
  },

  // 记录
  jilu: function(){
    var that = this;
    this.zhuanClose();
    var animation = wx.createAnimation({
      duration: 400,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(910).step()
    this.setData({
      animationData2: animation.export(),
      showShopPopup2: true
    })
    setTimeout(() => {
      animation.translateY(0).step()
      this.setData({
        animationData2: animation.export()
      })
    }, 200)

    $.Ajax("api/liveVideo", "POST", {
      id: that.data.VideoId
    }, function (res) {
      if (res.s) {
        that.setData({
          LuckDraw: res.d.userLuckDraw
        })
      }
    })
  },

  // 关闭记录
  jiluClose: function(){
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(910).step()
    this.setData({
      animationData2: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData2: animation.export(),
        showShopPopup2: false
      })
    }.bind(this), 200)
  },

  // 礼包
  libao: function(){
    var that = this;
    $.Ajax("api/userGift", "GET", {}, function (res) {
      if (res.s) {
        that.setData({
          Knapsack: res.d.userGift
        })
      } else {
        wx.showToast({
          title: res.m,
          icon: 'success',
          duration: 2000
        })
      }
    })
    that.zhuanClose();
    var animation = wx.createAnimation({
      duration: 400,
      timingFunction: "linear",
      delay: 0
    })
    that.animation = animation
    animation.translateY(630).step()
    that.setData({
      animationData3: animation.export(),
      showShopPopup3: true
    })
    setTimeout(() => {
      animation.translateY(0).step()
      that.setData({
        animationData3: animation.export()
      })
    }, 200)
  },

  // 点击礼包切换内容
  Clicklibao: function(e){
    var Index = e.currentTarget.dataset.index_;
    this.setData({
      libaoIndex: Index
    })
  },

  // 关闭礼包
  libaoClose: function(){
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(630).step()
    this.setData({
      animationData3: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData3: animation.export(),
        showShopPopup3: false
      })
    }.bind(this), 200)
  },

  // 点击打开我的账单
  MyBill: function(){
    wx.navigateTo({
      url: '../MyBill/MyBill',
    })
  },

  // 点击打开充值弹层
  TopUpS: function(){
    this.libaoClose();
    var animation = wx.createAnimation({
      duration: 400,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(722).step()
    this.setData({
      animationData6: animation.export(),
      showShopPopup6: true
    })
    setTimeout(() => {
      animation.translateY(0).step()
      this.setData({
        animationData6: animation.export()
      })
    }, 200)
  },

  // 选择充值额度
  TopUpSContBox_Click: function(e){
    var Index = e.currentTarget.dataset.index_;
    this.setData({
      TopUpSIndex: Index,
      TopUpSMoney: this.data.TopUpS[Index].money,
      TopUpSNumber: this.data.TopUpS[Index].number
    })
  },

  // 点击充值按钮
  TopUpSubmit: function(){
    var that = this;
    $.Ajax("api/addRecharge", "POST", {
      amount: that.data.TopUpSMoney,
      bean: that.data.TopUpSNumber
    }, function (res) {
      wx.showToast({
        title: res.m,
        icon: 'success',
        duration: 1500
      })
      if (res.s) {
        that.TopUpSClose();
        wx.requestPayment({
          timeStamp: res.d.config.timestamp,
          nonceStr: res.d.config.nonceStr,
          package: res.d.config.package,
          signType: res.d.config.signType,
          paySign: res.d.config.paySign,
          success: function (res) {
            $.Ajax("api/uindex", "GET", {}, function (res) {
              if (res.s) {
                that.setData({
                  UserInfor: res.d.user
                })
                wx.setStorageSync('UserInfor', res.d.user);
              }
            })
          },
          fail: function (res) {
            wx.showToast({
              title: "取消支付",
              icon: 'success',
              duration: 1500
            })
          }
        })
      }
    })
  },

  // 关闭充值弹层
  TopUpSClose: function () {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(722).step()
    this.setData({
      animationData6: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData6: animation.export(),
        showShopPopup6: false
      })
    }.bind(this), 200)
  },

  // 点击更多
  More: function(){
    this.setData({
      MoreStatus: false
    })
  },

  // 关闭更多
  MoreClose: function(){
    this.setData({
      MoreStatus: true
    })
  },

  // 排行榜
  Ranking: function () {
    var that = this;
    this.zhuanClose();
    this.setData({
      MoreStatus: true
    })
    var animation = wx.createAnimation({
      duration: 400,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(800).step()
    this.setData({
      animationData4: animation.export(),
      showShopPopup4: true
    })
    setTimeout(() => {
      animation.translateY(0).step()
      this.setData({
        animationData4: animation.export()
      })
    }, 200)
    $.Ajax("api/liveVideo", "POST", {
      id: that.data.VideoId
    }, function (res) {
      if (res.s) {
        that.setData({
          UserGifts: res.d.userGifts,
        })
      }
    })
  },

  // 排行榜关闭
  RankingClose: function(){
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(800).step()
    this.setData({
      animationData4: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData4: animation.export(),
        showShopPopup4: false
      })
    }.bind(this), 200)
  },

  // 点击玩法介绍
  Play: function(e){
    var that = this
    that.setData({
      MoreStatus: true
    })
    that.zhuanClose();
    var BgModuleSpeed = that.data.BgModuleSpeed;
    var BgModule = e.currentTarget.dataset.bgmodule;
    if (BgModule == "open") {
      that.setData({
        BgModule: true,
        ScrollY: false
      });
      var animation = wx.createAnimation({
        duration: BgModuleSpeed
      });
      animation.opacity(1).scale(1, 1).step();
      that.setData({
        animationData7: animation.export()
      })
    } else {
      var animation = wx.createAnimation({
        duration: BgModuleSpeed
      });
      animation.opacity(0).scale(2, 2).step();
      that.setData({
        animationData7: animation.export()
      })
      setTimeout(function () {
        that.setData({
          BgModule: false,
          ScrollY: true
        });
      }, BgModuleSpeed)
    }
  },

  // 点击观众列表
  Audien: function(){
    this.setData({
      MoreStatus: true
    })
    var animation = wx.createAnimation({
      duration: 400,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(800).step()
    this.setData({
      animationData5: animation.export(),
      showShopPopup5: true
    })
    setTimeout(() => {
      animation.translateY(0).step()
      this.setData({
        animationData5: animation.export()
      })
    }, 200)
  },

  // 点击关闭观众类表
  AudienClose: function(){
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(800).step()
    this.setData({
      animationData5: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData5: animation.export(),
        showShopPopup5: false
      })
    }.bind(this), 200)
  },

  // 点击Close退出本页面
  Close: function(){
    wx.navigateBack({
      delta: 1
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log('>>>[liveroom-room] onReady');
    var UserInfor = wx.getStorageSync('UserInfor');
    let timestamp = new Date().getTime();
    this.setData({
      UserInfor: UserInfor,
      userID: 'xcxU' + timestamp,
      userName: UserInfor.nickName + "_BoXin_" + UserInfor.avatarUrl,
      appID,
      publishStreamID: 'xcxS' + timestamp,
    });

    zg = new ZegoClient();
    zg.config({
      appid: this.data.appID,        // 必填，应用id，由即构提供
      idName: this.data.userID,      // 必填，用户自定义id
      nickName: this.data.userName,  // 必填，用户自定义昵称
      remoteLogLevel: 2,             // 日志上传级别，建议取值不小于 logLevel
      logLevel: 2,                   // 日志级别，debug: 0, info: 1, warn: 2, error: 3, report: 99, disable: 100（数字越大，日志越少）
      server: wsServerURL,        // 必填，服务器地址，由即构提供
      logUrl: logServerURL,   // 必填，log 服务器地址，由即构提供
      audienceCreateRoom: false,     // 观众不允许创建房间
    });
    this.bindCallBack();  //监听zego-sdk回调

    console.log('>>>[liveroom-room] publishStreamID is: ' + this.data.publishStreamID);

    // 进入房间，自动登录
    getLoginToken(this.data.userID, appID).then(token => {
      zg.setUserStateUpdate(true);
      console.log("token:" + token)
      this.loginRoom(token, self);
    });

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  bindCallBack() {

    let self = this;

    // startPlayStream、startPublishStream 后，服务端主动推过来的流更新事件
    // type: {play: 0, publish: 1};
    zg.onStreamUrlUpdate = function (streamid, url, type, reason) {
      console.log(">>>[liveroom-room] zg onStreamUrlUpdate, streamId: " + streamid + ', type: ' + (type === 0 ? 'play' : 'publish') + ', url: ' + url);

      if (type === 1) {
        self.setPushUrl(url);
      } else {
        self.setPlayUrl(streamid, url);
      }
    };

    // 服务端主动推过来的 连接断开事件
    zg.onDisconnect = function (err) {
      console.log(">>>[liveroom-room] zg onDisconnect");
    };

    // 服务端主动推过来的 用户被踢掉在线状态事件
    zg.onKickOut = function (err) {
      console.log(">>>[liveroom-room] zg onKickOut");
    };

    // 接收服务端主推送的自定义信令
    zg.onRecvCustomCommand = function (from_userid, from_idName, custom_content) {
      console.log(">>>[liveroom-room] zg onRecvCustomCommand" + "from_userid: " + from_userid + "from_idName: " + from_idName + "content: ");
      console.log(custom_content);
    };

    // 服务端主动推过来的 流的创建/删除事件；updatedType: { added: 0, deleted: 1 }；streamList：增量流列表
    zg.onStreamUpdated = function (updatedType, streamList) {
      console.log(">>>[liveroom-room] zg onStreamUpdated, updatedType: " + (updatedType === 0 ? 'added' : 'deleted') + ', streamList: ');
      console.log(streamList);

      if (updatedType === 1) {
        // 流删除通知触发事件：有推流成员正常退出房间；有推流成员停止推流；90s 超时。播放失败不会导致流删除
        self.stopPlayingStreamList(streamList);
      } else {
        // 有成员正常推流成功，流增加
        self.startPlayingStreamList(streamList);
      }
    };

    // 服务端主动推过来的 流信息中的 ExtraInfo更新事件（暂时不用实现）
    zg.onStreamExtraInfoUpdated = function (streamList) {
      console.log(">>>[liveroom-room] zg onStreamExtraInfoUpdated");
    };

    // 服务端主动推过来的 流的播放状态, 视频播放状态通知
    // type: { start:0, stop:1};
    zg.onPlayStateUpdate = function (updatedType, streamID) {
      console.log(">>>[liveroom-room] zg onPlayStateUpdate, " + (updatedType === 0 ? 'start ' : 'stop ') + streamID);

      if (updatedType === 1) {
        // 流播放失败, 停止拉流
        for (let i = 0; i < self.data.playStreamList.length; i++) {
          if (self.data.playStreamList[i]['streamID'] === streamID) {
            self.data.playStreamList[i]['playContext'] && self.data.playStreamList[i]['playContext'].stop();
            self.data.playStreamList[i]['playingState'] = 'failed';
            break;
          }
        }
      } else if (updatedType === 0) {
        // 流播放成功, 更新状态
        for (let i = 0; i < self.data.playStreamList.length; i++) {
          if (self.data.playStreamList[i]['streamID'] === streamID) {
            self.data.playStreamList[i]['playingState'] = 'succeeded';
          }
        }
      }

      self.setData({
        playStreamList: self.data.playStreamList,
      });
    };

    // 接收房间IM消息
    zg.onRecvRoomMsg = function (chat_data, server_msg_id, ret_msg_id) {
      console.log(">>>[liveroom-room] zg onRecvRoomMsg, data: ", chat_data);

      // 收到其他成员的回到前台通知
      let content = chat_data[0].msg_content;
      let category = chat_data[0].msg_category;

      var LiWuDongHua = chat_data[0].msg_content.split("_");
      if (LiWuDongHua[0] == "ZhangPengQQ812100002") {
        if (LiWuDongHua[1] == 1) {
          self.setData({
            DongHuaSrc: "https://sl.sx-sss.com/Uploads/20190611/5cff854444927.png",
            DongHuaBol: true,
          })
          setTimeout(function () {
            self.setData({
              DongHuaSrc: null,
              DongHuaBol: false
            })
          }, 1000)
        } else if (LiWuDongHua[1] == 2) {
          self.setData({
            DongHuaSrc: "https://sl.sx-sss.com/Uploads/20190611/5cff855696592.png",
            DongHuaBol: true,
          })
          setTimeout(function () {
            self.setData({
              DongHuaSrc: null,
              DongHuaBol: false
            })
          }, 1000)
        } else if (LiWuDongHua[1] == 3) {
          self.setData({
            DongHuaSrc: "https://sl.sx-sss.com/Uploads/20190611/5cff8565530d5.png",
            DongHuaBol: true,
          })
          setTimeout(function () {
            self.setData({
              DongHuaSrc: null,
              DongHuaBol: false
            })
          }, 1000)
        }
      }


      if (category === 2) {
        // 系统消息
        let data = content.split(".");
        let streamID = data[1];
        if (data[0] === "onShow") {
          for (let i = 0; i < self.data.playStreamList.length; i++) {
            if (self.data.playStreamList[i]["streamID"] === streamID && self.data.playStreamList[i]["playingState"] !== 'succeeded') {
              self.data.playStreamList[i]["playContext"] && self.data.playStreamList[i]["playContext"].stop();
              self.data.playStreamList[i]["playContext"] && self.data.playStreamList[i]["playContext"].play();
            }
          }
        }
      } else {
        // 评论消息
        let name = chat_data[0].id_name;
        let time = chat_data[0].send_time;

        let message = {};
        message.name = name;
        // message.time = format(time);
        message.content = content;
        message.id = name + time;
        var MsgCont = message.content.split("_");
        if (MsgCont[0] != "ZhangPengQQ812100002"){
          self.data.messageList.unshift(message);
          self.setData({
            messageList: self.data.messageList,
            scrollToView: message.id,
          });
        }
      }
    };

    // 服务端主动推过来的 流的质量更新
    zg.onPlayQualityUpdate = function (streamID, streamQuality) {
      console.log(">>>[liveroom-room] zg onPlayQualityUpdate", streamQuality);
    };

    // 推流后，服务器主动推过来的，流状态更新
    // type: { start: 0, stop: 1 }，主动停止推流没有回调，其他情况均回调
    zg.onPublishStateUpdate = function (type, streamid, error) {
      console.log('>>>[liveroom-room] zg onPublishStateUpdate, streamid: ' + streamid + ', type: ' + (type === 0 ? 'start' : 'stop') + ', error: ' + error);


      self.setData({
        isPublishing: type === 0 ? true : false,
        beginToPublish: false,
      });
      // 推流失败
      if (type == 1) {
        wx.showModal({
          title: '提示',
          content: '推流断开，请退出房间后重试',
          showCancel: false,
          success(res) {
            // 用户点击确定，或点击安卓蒙层关闭
            if (res.confirm || !res.cancel) {
              // 强制用户退出
              wx.navigateBack();
              zg.logout();
            }
          }
        });
      }
    };

    // 登录成功后，服务器主动推过来的，主播信息
    zg.onGetAnchorInfo = function (anchorId, anchorName) {
      console.log('>>>[liveroom-room] onGetAnchorInfo, anchorId: ' + anchorId + ', anchorName: ' + anchorName);

      self.setData({
        anchorID: anchorId,
        anchorName: anchorName,
      });
    };

    // 收到连麦请求
    zg.onRecvJoinLiveRequest = function (requestId, fromUserId, fromUsername, roomId) {
      console.log('>>>[liveroom-room] onRecvJoinLiveRequest, roomId: ' + roomId + 'requestUserId: ' + fromUserId + ', requestUsername: ' + fromUsername);

      self.data.requestJoinLiveList.push(requestId);

      let content = '观众 ' + fromUsername + ' 请求连麦，是否允许？';
      wx.showModal({
        title: '提示',
        content: content,
        success(res) {
          if (res.confirm) {
            console.log('>>>[liveroom-room] onRecvJoinLiveRequest accept join live');
            // self.switchPusherOrPlayerMode('pusher', 'RTC');

            // 已达房间上限，主播依然同意未处理的连麦，强制不处理
            if (self.data.reachStreamLimit) {
              wx.showToast({
                title: '房间内连麦人数已达上限，不建立新的连麦',
                icon: 'none',
                duration: 2000
              });
              zg.respondJoinLive(requestId, false); // true：同意；false：拒绝
            } else {
              zg.respondJoinLive(requestId, true); // true：同意；false：拒绝
            }


            self.handleMultiJoinLive(self.data.requestJoinLiveList, requestId, self);
          } else {
            console.log('>>>[liveroom-room] onRecvJoinLiveRequest refuse join live');
            zg.respondJoinLive(requestId, false); // true：同意；false：拒绝

            self.handleMultiJoinLive(self.data.requestJoinLiveList, requestId, self);
          }
        }
      });
    };

    // 收到停止连麦请求
    zg.onRecvEndJoinLiveCommand = function (requestId, fromUserId, fromUsername, roomId) {
      console.log('>>>[liveroom-room] onRecvEndJoinLiveCommand, roomId: ' + roomId + 'requestUserId: ' + fromUserId + ', requestUsername: ' + fromUsername);
    };

    zg.onUserStateUpdate = function (roomId, userList) {
      console.log(userList);
      if (userList.length === 1 && userList[0].role === 1 && userList[0].action === 2) {
        // 主播退出房间

        $.Ajax("api/luckDrawsCount","GET",{},function(res){
          if(res.s){
            if(res.d.num == 0){
              wx.showModal({
                title: '提示',
                content: '主播已离开，请前往其他房间观看',
                showCancel: false,
                success(res) {
                  // 用户点击确定，或点击安卓蒙层关闭
                  if (res.confirm || !res.cancel) {
                    // 强制用户退出
                    wx.navigateBack();
                    zg.logout();
                  }
                }
              });
            }else{
              wx.showModal({
                title: '提示',
                content: '主播已离开，剩余礼物下次继续',
                showCancel: false,
                success(res) {
                  // 用户点击确定，或点击安卓蒙层关闭
                  if (res.confirm || !res.cancel) {
                    // 强制用户退出
                    wx.navigateBack();
                    zg.logout();
                  }
                }
              });
            }
          }else{
            wx.navigateBack();
            zg.logout();
          }
        })
      }
    };
    zg.onUpdateOnlineCount = function (roomId, userCount) {
      self.setData({
        UserListNumber: userCount
      })
      console.log('>>>[liveroom-room] onUpdateOnlineCount, roomId: ' + roomId + ', userCount: ' + userCount);
    };

    zg.onGetTotalUserList = function (roomId, userList) {
      var UserListCont = [];
      for (var i=0; i<userList.length;i++){
        var nickName = userList[i].nickName.split("_BoXin_");
        UserListCont.push({
          UserName: nickName[0],
          Picture: nickName[1]
        })
      }
      self.setData({
        UserListCont: UserListCont
      })
    }
  },

  setPlayUrl(streamid, url) {
    console.log('>>>[liveroom-room] setPlayUrl: ', url);
    let self = this;
    if (!url) {
      console.log('>>>[liveroom-room] setPlayUrl, url is null');
      return;
    }

    for (let i = 0; i < self.data.playStreamList.length; i++) {
      if (self.data.playStreamList[i]['streamID'] === streamid && self.data.playStreamList[i]['playUrl'] === url) {
        console.log('>>>[liveroom-room] setPlayUrl, streamid and url are repeated');
        return;
      }
    }

    let streamInfo = {};
    let isStreamRepeated = false;

    // 相同 streamid 的源已存在，更新 Url
    for (let i = 0; i < self.data.playStreamList.length; i++) {
      if (self.data.playStreamList[i]['streamID'] === streamid) {
        isStreamRepeated = true;
        self.data.playStreamList[i]['playUrl'] = url;
        self.data.playStreamList[i]['playingState'] = 'initial';
        break;
      }
    }

    // 相同 streamid 的源不存在，创建新 player
    if (!isStreamRepeated) {
      streamInfo['streamID'] = streamid;
      streamInfo['playUrl'] = url;
      streamInfo['playContext'] = wx.createLivePlayerContext(streamid, self);
      streamInfo['playingState'] = 'initial';
      self.data.playStreamList.push(streamInfo);
    }

    self.setData({
      playStreamList: self.data.playStreamList,
    }, function () {
      // 检查流新增后，是否已经达到房间流上限
      if (self.data.playStreamList.length >= self.data.upperStreamLimit) {

        self.setData({
          reachStreamLimit: true,
        }, function () {
          wx.showToast({
            title: "房间内连麦人数已达上限，不允许新的连麦",
            icon: 'none',
            duration: 2000
          });
        });


      }

      //播放地址更新，需要重新停止再次播放
      if (isStreamRepeated) {
        self.data.playStreamList.forEach(streamInfo => {
          if (streamInfo.streamID == streamid) {
            streamInfo.playContext.stop();
            streamInfo.playingState = 'initial';
            streamInfo.playContext.play();
          }
        })
      }
    });

  },

  setPushUrl(url) {
    console.log('>>>[liveroom-room] setPushUrl: ', url);
    let self = this;

    if (!url) {
      console.log('>>>[liveroom-room] setPushUrl, url is null');
      return;
    }

    self.setData({
      pushUrl: url,
      pusherVideoContext: wx.createLivePusherContext("video-livePusher", self),
    }, function () {
      self.data.pusherVideoContext.stop();
      self.data.pusherVideoContext.start();

      // self.animation.rotate(720).step();
      // self.setData({animation: this.animation.export()});
    });
  },

  // 登录房间
  loginRoom(token) {
    let self = this;
    console.log('>>>[liveroom-room] login room, roomID: ' + self.data.roomID, ', userID: ' + self.data.userID + ', userName: ' + self.data.userName);

    zg.login(self.data.roomID, self.data.loginType === "anchor" ? 1 : 2, token, function (streamList) {
      console.log('>>>[liveroom-room] login success, streamList is: ');
      console.log(streamList);

      // 房间内已经有流，拉流
      self.startPlayingStreamList(streamList);

      // 主播登录成功即推流
      if (self.data.loginType === 'anchor') {
        console.log('>>>[liveroom-room] anchor startPublishingStream, publishStreamID: ' + self.data.publishStreamID);
        zg.setPreferPublishSourceType(self.data.preferPublishSourceType);
        zg.startPublishingStream(self.data.publishStreamID, '');
      } else {
        if (streamList.length === 0) {
          let title = '主播已经退出！';
          wx.showModal({
            title: '提示',
            content: title,
            showCancel: false,
            success(res) {
              if (res.confirm || !res.cancel) {
                wx.navigateBack();
              }
            }
          });
        }
      }

    }, function (err) {
      console.log('>>>[liveroom-room] login failed, error is: ', err);
      if (err) {
        let title = '登录房间失败，请稍后重试。\n失败信息：' + err.msg;
        wx.showModal({
          title: '提示',
          content: title,
          showCancel: false,
          success(res) {
            if (res.confirm || !res.cancel) {
              wx.navigateBack();
            }
          }
        });
      }
    });
  },

  startPlayingStreamList(streamList) {
    let self = this;

    if (streamList.length === 0) {
      console.log('>>>[liveroom-room] startPlayingStream, streamList is null');
      return;
    }


    zg.setPreferPlaySourceType(self.data.preferPlaySourceType);

    console.log('>>>[liveroom-room] startPlayingStream, preferPlaySourceType: ', self.data.preferPlaySourceType);

    // 获取每个 streamID 对应的拉流 url
    for (let i = 0; i < streamList.length; i++) {
      let streamID = streamList[i].stream_id;
      let anchorID = streamList[i].anchor_id_name;  // 推这条流的用户id
      console.log('>>>[liveroom-room] startPlayingStream, playStreamID: ' + streamID + ', pushed by : ' + anchorID);
      zg.startPlayingStream(streamID);
    }
  },

  stopPlayingStreamList(streamList) {
    let self = this;

    if (streamList.length === 0) {
      console.log('>>>[liveroom-room] stopPlayingStream, streamList is empty');
      return;
    }

    let playStreamList = self.data.playStreamList;
    for (let i = 0; i < streamList.length; i++) {
      let streamID = streamList[i].stream_id;

      console.log('>>>[liveroom-room] stopPlayingStream, playStreamID: ' + streamID);
      zg.stopPlayingStream(streamID);

      // 删除播放流列表中，删除的流
      for (let j = 0; j < playStreamList.length; j++) {
        if (playStreamList[j]['streamID'] === streamID) {
          console.log('>>>[liveroom-room] stopPlayingStream, stream to be deleted: ');
          console.log(playStreamList[j]);

          playStreamList[j]['playContext'] && playStreamList[j]['playContext'].stop();

          let content = '一位观众结束连麦，停止拉流';
          wx.showToast({
            title: content,
            icon: 'none',
            duration: 2000
          });

          playStreamList.splice(j, 1);
          break;
        }
      }
    }

    self.setData({
      playStreamList: playStreamList,
    }, function () {
      // 检查流删除后，是否低于房间流上限
      if (self.data.playStreamList.length === self.data.upperStreamLimit - 1) {
        self.setData({
          reachStreamLimit: false,
        }, function () {
          if (self.data.loginType === "audience") {
            wx.showToast({
              title: "一位观众结束连麦，允许新的连麦",
              icon: 'none',
              duration: 2000
            });
          }
        });
      }

      // 主播结束了所有的连麦，切换回 live 模式   （可选）
      if (self.data.loginType === 'anchor' && self.data.playStreamList.length === 0) {
        // self.switchPusherOrPlayerMode('pusher', 'live');
      }


    });
  },

  //live-player 绑定拉流事件
  onPlayStateChange(e) {
    console.log('>>>[liveroom-room] onPlayStateChange, code: ' + e.detail.code + ', message:' + e.detail.message);
    // 透传拉流事件给 SDK，type 0 拉流
    zg.updatePlayerState(e.currentTarget.id, e, 0);

    if (e.detail.code === 2002 || e.detail.code === 2004) {
      this.updatePlayingStateOnly(e, 'succeeded');
    } else if (e.detail.code === -2301) {
      this.updatePlayingStateOnly(e, 'failed');
    }
  },

  // 主播异常操作，导致拉流端 play 失败，此时不会影响 SDK 内部拉流状态，但需要额外处理 live-player 状态
  updatePlayingStateOnly(e, newState) {
    for (let index in this.data.playStreamList) {
      let playStream = this.data.playStreamList[index];
      if (playStream.streamID === e.currentTarget.id && playStream.playingState !== newState) {
        playStream.playingState = newState;
        this.setData({
          playStreamList: this.data.playStreamList,
        })
        break;
      }
    }
  },

  // live-pusher 绑定推流事件
  onPushStateChange(e) {
    console.log('>>>[liveroom-room] onPushStateChange, code: ' + e.detail.code + ', message:' + e.detail.message);
    // 透传推流事件给 SDK，type 1 推流
    zg.updatePlayerState(this.data.publishStreamID, e, 1);
  },

  // live-player 绑定网络状态事件
  onPlayNetStateChange(e) {
    //透传网络状态事件给 SDK，type 0 拉流
    zg.updatePlayerNetStatus(e.currentTarget.id, e, 0);
  },

  // live-pusher 绑定网络状态事件
  onPushNetStateChange(e) {
    //透传网络状态事件给 SDK，type 1 推流
    console.log('quality', e);
    zg.updatePlayerNetStatus(this.data.publishStreamID, e, 1);
  },

  // 主播邀请连麦
  inviteJoinLive() {
    console.log('>>>[liveroom-room] inviteJoinLive');

    zg.inviteJoinLive('', function (res) {
      console.log('>>>[liveroom-room] inviteJoinLive sent succeeded');
    }, function (error) {
      console.log('>>>[liveroom-room] inviteJoinLive sent failed, error: ', error);
    }, function (result, userID, userName) {
      console.log('>>>[liveroom-room] inviteJoinLive, result: ' + result);
    });
  },

  // 观众请求连麦，或主播邀请连麦
  requestJoinLive() {
    this.CatalogClose();
    let self = this;


    if (this.data.loginType === 'anchor') return;
    // 防止两次点击操作间隔太快
    let nowTime = new Date();
    if (nowTime - self.data.tapTime < 1000) {
      return;
    }
    self.setData({ 'tapTime': nowTime });

    // 正在发起连麦中，不处理
    if (self.data.beginToPublish === true) {
      console.log('>>>[liveroom-room] begin to publishing, ignore');
      return;
    }

    // 房间流已达上限，不处理
    if (self.data.reachStreamLimit === true) {
      console.log('>>>[liveroom-room] reach stream limit, ignore');
      return;
    }


    // 观众正在连麦时点击，则结束连麦
    if (self.data.isPublishing) {
      zg.endJoinLive(self.data.anchorID, function (result, userID, userName) {
        console.log('>>>[liveroom-room] endJoinLive, result: ' + result);
      }, null);

      // 停止推流
      zg.stopPublishingStream(self.data.publishStreamID);
      self.data.pusherVideoContext.stop();


      self.setData({
        isPublishing: false,
        pushUrl: "",
      }, function () {
        // 自己停止推流，不会收到流删减消息，所以此处需要主动调整视图大小
      });


      // setTimeout(() => {
      //     // 回前台重新拉流
      //     for (let i = 0; i < this.data.playStreamList.length; i++) {
      //         zg.startPlayingStream(this.data.playStreamList[i]['streamID']);
      //         this.data.playStreamList[i]['playContext'] && this.data.playStreamList[i]['playContext'].play();
      //     }
      // }, 500);
      return;
    }

    // 观众未连麦，点击开始推流
    console.log('>>>[liveroom-room] audience requestJoinLive');
    self.setData({
      beginToPublish: true,
    });

    zg.requestJoinLive(self.data.anchorID, function (res) {
      console.log('>>>[liveroom-room] requestJoinLive sent succeeded');
    }, function (error) {
      console.log('>>>[liveroom-room] requestJoinLive sent failed, error: ', error);
    }, function (result, userID, userName) {
      console.log('>>>[liveroom-room] requestJoinLive, result: ' + result);

      // 待补充，校验 userID
      if (result === false) {
        wx.showToast({
          title: '主播拒绝连麦',
          icon: 'none',
          duration: 2000
        });

        self.setData({
          beginToPublish: false,
        })
      } else {
        // 主播同意了连麦，但此时已经达到了房间流上限，不再进行连麦
        if (self.data.reachStreamLimit) {
          self.setData({
            beginToPublish: false,
          });
          return;
        }

        wx.showToast({
          title: '主播同意连麦，准备推流',
          icon: 'none',
          duration: 2000
        });

        // 主播同意连麦后，观众开始推流
        console.log('>>>[liveroom-room] startPublishingStream, userID: ' + userID + ', publishStreamID: ' + self.data.publishStreamID);
        zg.setPreferPublishSourceType(self.data.preferPublishSourceType);
        zg.startPublishingStream(self.data.publishStreamID, '');


      }
    });
  },


  handleMultiJoinLive(requestJoinLiveList, requestId, self) {
    for (let i = 0; i < requestJoinLiveList.length; i++) {
      if (requestJoinLiveList[i] != requestId) {
        // 新的连麦弹框会覆盖旧的弹框，拒绝被覆盖的连麦请求
        zg.respondJoinLive(requestJoinLiveList[i], false);
      }
    }
  },

  // 推流画面配置
  switchCamera() {
    this.data.pushConfig.frontCamera = !this.data.pushConfig.frontCamera;
    this.setData({
      pushConfig: this.data.pushConfig,
    });
    this.data.pusherVideoContext && this.data.pusherVideoContext.switchCamera();
  },

  setBeauty() {
    this.data.pushConfig.isBeauty = (this.data.pushConfig.isBeauty === 0 ? 6 : 0);
    this.setData({
      pushConfig: this.data.pushConfig,
    });
  },

  enableMute() {
    this.data.pushConfig.isMute = !this.data.pushConfig.isMute;
    this.setData({
      pushConfig: this.data.pushConfig,
    });
  },

  showLog() {
    this.data.pushConfig.showLog = !this.data.pushConfig.showLog;
    this.setData({
      pushConfig: this.data.pushConfig,
    });
  },

  bindMessageInput: function (e) {
    this.data.inputMessage = e.detail.value;
  },
  onComment() {
    if (this.data.inputMessage == '' || this.data.inputMessage == null){
      wx.showToast({
        title: '请填写弹幕消息',
        icon: 'none',
        duration: 3000,
        mask: true
      })
    }else{
      var userName = this.data.userName.split("_BoXin_");
      let message = {
        id: this.data.userID + Date.parse(new Date()),
        name: userName[0],
        content: this.data.inputMessage,
      };
      this.data.messageList.unshift(message);
      console.log('>>>[liveroom-room] currentMessage', this.data.inputMessage);
      this.setData({
        messageList: this.data.messageList,
        inputMessage: "",
        scrollToView: message.id,
      });
      this.showMessage();
      var self = this;
      zg.sendRoomMsg(1, 1, message.content,
        function (seq, msgId, msg_category, msg_type, msg_content) {
          console.log('>>>[liveroom-room] onComment success');
          self.setData({
            inputMessage: null
          })
        }, function (err, seq, msg_category, msg_type, msg_content) {
          console.log('>>>[liveroom-room] onComment, error: ');
          console.log(err);
        });
    }
  },

  showMessage() {
    console.log('>>>[liveroom-room] onShowMessage');

    this.setData({
      isMessageHide: !this.data.isMessageHide
    });

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this;
    $.Ajax("api/zhuangban", "POST", {
      add: 0
    }, function (res) {
      if(res.s){
        if (res.d.isClose != 0){
          that.setData({
            RoomText: res.d.title,
            RoomCont: res.d.content
          })
        }else{
          that.setData({
            RoomText: null,
            RoomCont: null
          })
        }
      }
    })

    // 回前台重新拉流
    for (let i = 0; i < this.data.playStreamList.length; i++) {
      zg.startPlayingStream(this.data.playStreamList[i]['streamID']);
      this.data.playStreamList[i]['playContext'] && this.data.playStreamList[i]['playContext'].play();
    }


    // 如果正在推流，回到前台，通知其他成员，使其触发拉流
    if (this.data.isPublishing) {
      console.log('>>>[liveroom-room] sendRoomMsg, begin to send');

      let roomData = "onShow." + this.data.publishStreamID;
      zg.sendRoomMsg(2, 1, roomData,
        function (seq, msgId, msg_category, msg_type, msg_content) {
          console.log('>>>[liveroom-room] sendRoomMsg, send succeeded');
        },
        function (err, seq, msg_category, msg_type, msg_content) {
          console.log('>>>[liveroom-room] sendRoomMsg, send failed, err: ', err);
        }
      );
    }


    //刷新全局变量
    appID = getApp().globalData.liveAppID;
    wsServerURL = getApp().globalData.wsServerURL;
    logServerURL = getApp().globalData.logServerURL;
    tokenURL = getApp().globalData.tokenURL;
  },

  RoomClick: function(){
    wx.showModal({
      title: this.data.RoomText,
      content: this.data.RoomCont,
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log('>>>[liveroom-room] onHide');

    // 退后台停止拉流
    for (let i = 0; i < this.data.playStreamList.length; i++) {
      console.log('>>>[liveroom-room] onHide stopPlayStream: ', this.data.playStreamList[i]['streamID']);
      zg.stopPlayingStream(this.data.playStreamList[i]['streamID']);
      this.data.playStreamList[i].playUrl = "";
      this.data.playStreamList[i]['playContext'] && this.data.playStreamList[i]['playContext'].stop();
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log('>>>[liveroom-room] onUnload');

    // 停止拉流
    let streamList = this.data.playStreamList;
    for (let i = 0; i < streamList.length; i++) {
      let streamID = streamList[i]['streamID'];
      console.log('>>>[liveroom-room] onUnload stop play stream, streamid: ' + streamID);
      zg.stopPlayingStream(streamID);

      streamList[i]['playContext'] && streamList[i]['playContext'].stop();
    }

    this.setData({
      playStreamList: [],
    });

    // 停止推流
    if (this.data.isPublishing) {
      console.log('>>>[liveroom-room] stop publish stream, streamid: ' + this.data.publishStreamID);
      zg.stopPublishingStream(this.data.publishStreamID);
      this.setData({
        publishStreamID: "",
        isPublishing: false,
        pushUrl: "",
      });

      this.data.pusherVideoContext.stop();
    }

    // 停止连麦

    // 退出登录
    zg.logout();
  },

  error(e) {
    console.error('live-player error:', e.detail.errMsg)
  },

})